<!--通过设备类型选择设备型号-->
<template>
  <BasicModal v-bind="$attrs" @register="register" :title="modalTitle" width="1200px" @ok="handleOk" destroyOnClose @visible-change="visibleChange">
    <a-row :gutter="10">
      <a-col :md="7" :sm="24">
        <a-card :style="{ minHeight: '613px', overflow: 'auto' }">
          <!--设备类型-->
          <BasicTree
            title="设备类型"
            ref="treeRef"
            :style="{ minWidth: '250px' }"
            :treeData="treeData" 
            toolbar 
            showLine  
            :fieldNames="fieldNames" 
            :checkable="false"
            @select="onSelect"
            :selectedKeys="selectedKeys"
            :clickRowToExpand="false"
          />
        </a-card>
      </a-col>
      <a-col :md="17" :sm="24">
        <a-card :style="{ minHeight: '613px', overflow: 'auto' }">
          <!--设备型号列表-->
          <BasicTable ref="tableRef" v-bind="getBindValue" :searchInfo="searchInfo" :api="deviceModelList" :rowSelection="rowSelection" />
        </a-card>
      </a-col>
    </a-row>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, unref, ref, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTree } from '/@/components/Tree/index';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { useSelectBiz } from '/@/components/Form/src/jeecg/hooks/useSelectBiz';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { columns, searchFormSchema } from '../deviceModel.data';
  import { list as deviceTypeList } from '../../deviceType/deviceType.api';
  import { list as deviceModelList } from '../deviceModel.api';
  import { selectProps } from '/@/components/Form/src/jeecg/props/props';
  export default defineComponent({
    name: 'DevSelectByDepModal',
    components: {
      //此处需要异步加载BasicTable
      BasicModal,
      BasicTree,
      BasicTable: createAsyncComponent(() => import('/@/components/Table/src/BasicTable.vue'), {
        loading: true,
      }),
    },
    props: {
      ...selectProps,
      //选择框标题
      modalTitle: {
        type: String,
        default: '选择',
      },
    },
    emits: ['register', 'getSelectResult'],
    setup(props, { emit, refs }) {
      const tableRef = ref();
      const treeRef = ref();
      const attrs = useAttrs();
      // 树与数据字段映射
      const fieldNames = {title: 'name',key: 'id'};
      const treeData = ref([]);
      // 当前选中的项
      const selectedKeys = ref<any[]>([]);
      const searchInfo = {};
      
      //注册弹框
      const [register, { closeModal }] = useModalInner(async (data) => {
        await loadTreeData();
        const deviceTypeId = data.deviceTypeId;
        getTree().setSelectedKeys([deviceTypeId]);
        searchInfo['typeId'] = deviceTypeId;
      });
      
      /**
       *表格配置
       */
      const tableProps = {
        columns: columns,
        useSearchForm: true,
        canResize: false,
        showIndexColumn: false,
        striped: true,
        bordered: true,
        size: 'small',
        // rowSelection: {
        //   type: 'radio',
        //   onChange: handleOnChange,
        // },
        clickToRowSelect: true,
        formConfig: {
          //labelWidth: 200,
          baseColProps: {
            xs: 24,
            sm: 8,
            md: 6,
            lg: 8,
            xl: 6,
            xxl: 10,
          },
          //update-begin-author:liusq date:2023-10-30 for: [issues/5514]组件页面显示错位
          actionColOptions: {
            xs: 24,
            sm: 12,
            md: 12,
            lg: 12,
            xl: 8,
            xxl: 8,
          },
          //update-end-author:liusq date:2023-10-30 for: [issues/5514]组件页面显示错位
          schemas: searchFormSchema,
          resetFunc: customResetFunc,
        },
      };
      const getBindValue = Object.assign({},  unref(props), unref(attrs), tableProps, {isRadioSelection: 'radio'});
      const [{ rowSelection, visibleChange, indexColumnProps, getSelectResult, reset }] = useSelectBiz(deviceModelList, getBindValue);


      // 加载设备类型信息
      function loadTreeData() {
        treeData.value = [];
        deviceTypeList({})
          .then((res) => {
            if (res.success) {
              if (res.data && Array.isArray(res.data)) {
                treeData.value = res.data;
                expandAll(true);
              }
            }
          });
      }

      function getTree() {
        const tree = unref(treeRef);
        if (!tree) {
          throw new Error('tree is null!');
        }
        return tree;
      }

      // 展开全部|折叠全部
      async function expandAll(checkAll: boolean) {
        await nextTick(); //防止无法默认展开数据
        getTree().expandAll(checkAll);
      }

      /**
       * 点击树节点,筛选出对应的设备型号
       */
      function onSelect(selKeys, event) {
        if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
          setSelectedKey(selKeys[0], event.selectedNodes[0]);
        } else {
          // 这样可以防止用户取消选择
          setSelectedKey(selectedKeys.value[0]);
        }
      }

       /**
       * 设置当前选中的行
       */
      function setSelectedKey(key: string, data?: object) {
        if (data) {
          searchInfo['typeId'] = data.id;
          tableRef.value.reload();
        }
      }

      async function handleOnChange(selectedRowKeys, selectedRows) {
        if (selectedRows && selectedRows.length > 0) {
          // state.weixinTitle = selectedRows[0].name;
          // state.weixinAppId = selectedRows[0].appid;
          // getMenu();
        } else {
          // clearMenu();
        }
      }

      /**
       * 自定义重置方法
       * */
      async function customResetFunc() {
        console.log('自定义查询');
        //树节点清空
        selectedKeys.value = [];
        //查询条件清空
        searchInfo['typeId'] = '';
        //选择项清空
        reset();
      }

      /**
       * 确定选择
       */
      function handleOk() {
        getSelectResult((options, values) => {
          //回传选项和已选择的值
          emit('getSelectResult', options, values);
          //关闭弹窗
          closeModal();
        });
      }

      return {
        //config,
        handleOk,
        searchInfo,
        register,
        indexColumnProps,
        visibleChange,
        getBindValue,
        rowSelection,

        fieldNames,
        treeData,
        selectedKeys,
        treeRef,
        tableRef,
        deviceModelList,
        onSelect
      };
    },
  });
</script>

<style scoped lang="less"></style>
